﻿///***************************************************************
/// 시  스  템 : Updms.Ref
/// 단위시스템 : REF
/// 계      층 : Presentation Layer
/// 프로그램명 : Ref1010m
/// 파  일  명 : Ref1010m.aspx.cs
/// 설      명 : 활력업소관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2013-03-21 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.Page;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Ref.Exe;

namespace Updms.Ref
{
	public partial class Ref1010m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		public static readonly string PID = "Ref1010m";
		public static readonly string gs_path_info = "/updms/Ref/" + PID + ".aspx";

		Global global = new Global();
		AccessCheck access = new AccessCheck();
		CommCode.Com com = new CommCode.Com(LANG_SET);
		CommCode.Ref rfs = new CommCode.Ref(LANG_SET);

		//페이징
		private int li_cur_page, li_row_count, li_st_page, li_ed_page;
		protected int li_page_size = GRID_PAGESIZE;// 한 페이지에 출력될 행의수

		//검색
		protected string kw1 = "";	//업종
		protected string kw2 = "";	//업소명
		protected string kw3 = "";	//위치
		protected string kw4 = "";	//즐겨찾기

		//메뉴 선택값
		protected string gs_sm = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SearchProcess();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetSearchCategory();
			SetSearchFavoriteYn();
			SetFavoriteYn();
			SetNewShopId();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript

		private void SetClientScript()
		{
			//onKeyPress이벤트 (엔터검색)
			txt_search_shop_nm.Attributes.Add("onkeypress", "enterSearch(event)");
			txt_search_address.Attributes.Add("onkeypress", "enterSearch(event)");
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			if (Request.QueryString["page"] == null || int.Parse(Request.QueryString["page"]) == 1)
			{
				li_cur_page = 1;
				li_st_page = 0;
				li_ed_page = li_page_size;
			}
			else
			{
				li_cur_page = int.Parse(Request.QueryString["page"]);
				li_st_page = (int.Parse(Request.QueryString["page"]) - 1) * li_page_size;
				li_ed_page = li_st_page + li_page_size;
			}

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_category.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_category.SelectedValue = kw1;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						kw2 = txt_search_shop_nm.Text.Trim();
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						txt_search_shop_nm.Text = kw1;
					}
					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))	// url에 값이 없으면
					{
						kw3 = txt_search_address.Text.Trim();
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						txt_search_address.Text = kw2;
					}
					if (String.IsNullOrEmpty(Request.QueryString["kw4"]))	// url에 값이 없으면
					{
						kw4 = ddl_search_favorite_yn.SelectedValue;
					}
					else
					{
						kw4 = Server.UrlDecode(Request.QueryString["kw4"]);
						ddl_search_favorite_yn.SelectedValue = kw4;
					}
					break;
				case "SEARCH":
					kw1 = ddl_search_category.SelectedValue;
					kw2 = txt_search_shop_nm.Text.Trim();
					kw3 = txt_search_address.Text.Trim();
					kw4 = ddl_search_favorite_yn.SelectedValue;
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			string ls_kw1 = ConversionUtil.CompareReplace(ddl_search_category.SelectedItem.Text, DDL_SELECT, "-");
			lbl_search_keyword.Text = ls_kw1 + " / " + kw2 + " / " + kw3 + " / " + kw4;
		}

		#endregion

		#region 마스터 Method (SetSearchCategory, SetSearchFavoriteYn)

		//업종
		private void SetSearchCategory()
		{
			rfs.SetCategory(ddl_search_category);
			rfs.SetCategory(ddl_category);
			ddl_search_category.Items.Insert(0, new ListItem(DDL_SELECT, ""));
		}

		//즐겨찾기
		private void SetSearchFavoriteYn()
		{
			com.SetUseYn(ddl_search_favorite_yn);
			ddl_search_favorite_yn.Items.Insert(0, new ListItem(DDL_SELECT, ""));
		}

		#endregion

		#region 디테일 Method (SetNewShopId, SetFavoriteYn)

		//신규업소아이디
		private void SetNewShopId()
		{
			lbl_shop_id.Text = global.GetNewIdByTable("UPDMS_REF_SHOP", "Shop_Id", "SP");
		}

		//즐겨찾기
		private void SetFavoriteYn()
		{
			com.SetUseYn(rbl_favorite_yn);
		}

		#endregion

		#region CRUD (SelectProcess, InsertProcess, UpdateProcess, DeleteProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			int li_page_count;

			//검색
			lo_dp.AddProperty("ls_category", typeof(string), kw1);
			lo_dp.AddProperty("ls_shop_nm", typeof(string), kw2);
			lo_dp.AddProperty("ls_address", typeof(string), kw3);
			lo_dp.AddProperty("ls_favorite_yn", typeof(string), kw4);

			using (Ref1010m_NT _Ref1010m_NT = new Ref1010m_NT())
			{
				li_row_count = _Ref1010m_NT.GetSearchCount(lo_dp);	// 검색된 행수
				li_page_count = (int)((li_row_count - 1) / li_page_size) + 1;	// 총페이지수 계산

				//모두보기/페이징
				lo_dp.AddProperty("li_st_page", typeof(Int32), (cb_list_all.Checked) ? 0 : li_st_page);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), (cb_list_all.Checked) ? li_row_count : li_ed_page);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
				lbl_page.Visible = !cb_list_all.Checked;

				lo_ds.Merge(_Ref1010m_NT.SelectProcess(lo_dp));

				GridView1.DataSource = lo_ds;
				GridView1.DataBind();

				Pager pager = new Pager(this, ref lbl_page);
				pager.PageNavigation(
					li_cur_page,
					li_page_count,
					gs_path_info + "?sm=" + gs_sm + "&kw1=" + Server.UrlEncode(kw1) + "&kw2=" + Server.UrlEncode(kw2) + "&kw3=" + Server.UrlEncode(kw3) + "&kw4=" + Server.UrlEncode(kw4) + "&page=");

				//결과출력(키워드, 검색행수)
				ShowKeywordLabel();
				lbl_result_count.Text = li_row_count.ToString("#,###,##0");
			}
		}

		//저장
		private void InsertProcess()
		{
			using (Ref1010m_RT _Ref1010m_RT = new Ref1010m_RT())
			{
				int li_return = _Ref1010m_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//수정
		private void UpdateProcess()
		{
			using (Ref1010m_RT _Ref1010m_RT = new Ref1010m_RT())
			{
				int li_return = _Ref1010m_RT.UpdateProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//삭제
		private void DeleteProcess(string ls_xml)
		{
			using (Ref1010m_RT _Ref1010m_RT = new Ref1010m_RT())
			{
				int li_return = _Ref1010m_RT.DeleteProcess(ls_xml);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_004" : "MSG_ERR_103";	//삭제되었습니다:삭제할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//즐겨찾기설정
		private void SetFavorite(int li_seq)
		{
			DataPack lo_dp = new DataPack();
			lo_dp.AddProperty("li_seq", typeof(int), li_seq);
			lo_dp.AddProperty("ls_user_id", typeof(string), USER_ID);

			// Source
			using (Ref1010m_RT _Ref1010m_RT = new Ref1010m_RT())
			{
				int li_return = _Ref1010m_RT.SetFavorite(lo_dp);
			}
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			ClearValue();
			SelectProcess();
		}

		#endregion

		#region SetValue, ClearValue

		//SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();
			lo_dp.AddProperty("Seq",			typeof(string), lbl_pk.Text);	//순번
			lo_dp.AddProperty("Category",		typeof(string), ddl_category.SelectedValue);	//업종
			lo_dp.AddProperty("Shop_Id",		typeof(string), lbl_shop_id.Text);	//업소ID
			lo_dp.AddProperty("Shop_Nm",		typeof(string), txt_shop_nm.Text);	//업소명
			lo_dp.AddProperty("Reserve_Phone",	typeof(string), ConversionUtil.DefaultValue(txt_reserve_phone.Text));	//예약번호
			lo_dp.AddProperty("Address",		typeof(string), ConversionUtil.DefaultValue(txt_address.Text));	//주소
			lo_dp.AddProperty("Latitude",		typeof(string), ConversionUtil.DefaultValue(txt_latitude.Text, ""));	//위도
			lo_dp.AddProperty("Longitude",		typeof(string), ConversionUtil.DefaultValue(txt_longitude.Text, ""));	//경도
			lo_dp.AddProperty("Favorite_Yn",	typeof(string), rbl_favorite_yn.SelectedValue);	//즐겨찾기
			lo_dp.AddProperty("Remark",			typeof(string), ConversionUtil.DefaultValue(txt_remark.Text));	//비고
			lo_dp.AddProperty("Create_User",	typeof(string), USER_ID);	//최초등록자
			lo_dp.AddProperty("Create_Dt",		typeof(string), "");	//최초등록일
			lo_dp.AddProperty("Update_User",	typeof(string), USER_ID);	//최종수정자
			lo_dp.AddProperty("Update_Dt",		typeof(string), "");	//최종수정일

			return lo_dp;
		}

		//ClearValue
		private void ClearValue()
		{
			lbl_pk.Text = "";
			h_no.Value = "";
			ddl_category.SelectedIndex = 0;
			txt_shop_nm.Text = "";	//업소명
			txt_reserve_phone.Text = "";	//예약번호
			txt_address.Text = "";	//주소
			txt_latitude.Text = "";	//위도
			txt_longitude.Text = "";	//경도
			rbl_favorite_yn.SelectedIndex = 0;	//즐겨찾기
			txt_remark.Text = "";	//비고
			SetNewShopId();
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				//접근권한 체크
				if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
				{
					Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
				}
				//사용권한별 버튼처리
				PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
			}
			ChangePageMode();

			//페이지모드 처리
			string ls_class = String.IsNullOrEmpty(lbl_pk.Text) ? "sbtn sbtn_mode_i" : "sbtn sbtn_mode_u";
			string ls_title = String.IsNullOrEmpty(lbl_pk.Text) ? "입력" : "수정";
			btn_chg_mode.Attributes.Add("class", ls_class);
			btn_chg_mode.Attributes.Add("title", ls_title);
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;

			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", "overBackground('GridView1', " + (e.Row.RowIndex + 1) + ")");
				e.Row.Attributes.Add("onmouseout", "outBackground('GridView1', 1)");

				//번호
				e.Row.Cells[1].Text = cb_list_all.Checked
					? (li_row_count - e.Row.RowIndex).ToString()
					: ((li_row_count - ((li_cur_page - 1) * li_page_size)) - e.Row.RowIndex).ToString();
			}
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			GridView gv = (GridView)sender;
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

			LinkButton lbtn_rc = (LinkButton)GridView1.Rows[row.RowIndex].FindControl("lbtn_rc");

			//row.Cells[0].Text.ToString();													//0.체크박스
			h_no.Value = row.Cells[1].Text.ToString();										//1.번호
			lbl_pk.Text = gv.DataKeys[row.RowIndex].Values["Seq"].ToString();				//2.Seq
			lbl_shop_id.Text = gv.DataKeys[row.RowIndex].Values["Shop_Id"].ToString();		//3.Shop_Id
			ddl_category.SelectedValue = gv.DataKeys[row.RowIndex].Values["Category"].ToString();//4.Category
																							//5.Category_Nm
			txt_shop_nm.Text = lbtn_rc.Text;												//6.Shop_Nm(template)
			txt_reserve_phone.Text = row.Cells[7].Text.ToString();							//7.Reserve_Phone
			txt_address.Text = row.Cells[8].Text.ToString();								//8.Address
																							//9.NaverMap_Link
			txt_latitude.Text = gv.DataKeys[row.RowIndex].Values["Latitude"].ToString();	//10.Latitude
			txt_longitude.Text = gv.DataKeys[row.RowIndex].Values["Longitude"].ToString();	//11.Longitude
			rbl_favorite_yn.SelectedValue = gv.DataKeys[row.RowIndex].Values["Favorite_Yn"].ToString();	//12.Favorite_Yn
																							//13.Favorite_Yn_Icon
			txt_remark.Text = row.Cells[14].Text.ToString();								//14.Remark
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			if (global.CheckSaveMode("UPDMS_REF_SHOP", "Seq", lbl_pk.Text.Trim()))
			{
				UpdateProcess();
			}
			else
			{
				InsertProcess();
			}
		}

		//삭제
		protected void ibtn_delete_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");

			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();
					sb.Append("<UPDMS_REF_SHOP>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("</UPDMS_REF_SHOP>");
				}
			}
			sb.Append("</UPDMS>");

			DeleteProcess(sb.ToString());
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_category", typeof(string), kw1);
			lo_dp.AddProperty("ls_shop_nm", typeof(string), kw2);
			lo_dp.AddProperty("ls_address", typeof(string), kw3);
			lo_dp.AddProperty("ls_favorite_yn", typeof(string), kw4);
			
			using (Ref1010m_NT _Ref1010m_NT = new Ref1010m_NT())
			{
				li_row_count = _Ref1010m_NT.GetSearchCount(lo_dp);

				lo_dp.AddProperty("li_st_page", typeof(Int32), 0);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), li_row_count);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

				lo_ds.Merge(_Ref1010m_NT.SelectProcess(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//모두보기
		protected void cb_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//디테일 초기화
		protected void lbtn_init_detail_Click(object sender, EventArgs e)
		{
			ClearValue();
		}

		//페이지모드변경
		protected void lbtn_chg_mode_Click(object sender, EventArgs e)
		{
			h_no.Value = "";
			lbl_pk.Text = "";
			SetNewShopId();
		}

		//즐겨찾기설정(리스트에서)
		protected void lbtn_favorite_Click(object sender, EventArgs e)
		{
			if (access.CheckPgmUsingGrant(USER_DIV, PID))
			{
				SetFavorite(Convert.ToInt32(h_seq.Value));
				SearchProcess();
			}
			else
			{
				CallMsgBoxInAjax("MSG_ERR_109");	//작업에 필요한 권한이 없습니다
			}
		}

		#endregion

	}
}